package com.powernode.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.powernode.common.Constants;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 描述：生成一个验证码，以图片流的形式响应给页面
 */
@RestController
@RequestMapping("captcha")
public class CodeController {

    /**
     * 生成一个验证码，使用HttpServletResponse响应一个图片出去
     */
    @RequestMapping("captcha.action")
    public void captcha(HttpSession session, HttpServletResponse response){
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 76,1,200);
        //得到正确的验证码
        String code = lineCaptcha.getCode();
        //把正确的验证码放到session
        session.setAttribute(Constants.CAPTCHA_CODE_KEY,code);
        //再把验证码的图片响应给客户端
        try {
            lineCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}